/*
 * Copyright (c) 2023-2025 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.system.sys.controller;

import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import org.elsfs.cloud.api.security.entity.SecurityUserEntity;
import org.elsfs.cloud.api.security.utils.SecurityUtils;
import org.elsfs.cloud.common.core.vo.R;
import org.elsfs.cloud.common.util.lang.CollectionUtils;
import org.elsfs.cloud.module.config.api.constant.SystemConfigConstantKey;
import org.elsfs.cloud.module.config.api.entity.ConfigEntity;
import org.elsfs.cloud.module.config.api.service.SysConfigService;
import org.elsfs.cloud.permission.api.entity.SysMenu;
import org.elsfs.cloud.permission.api.service.SysMenuService;
import org.elsfs.cloud.system.sys.repository.mapper.SysDeptMenuMapper;
import org.elsfs.cloud.system.sys.repository.mapper.SysRoleMenuMapper;
import org.elsfs.cloud.system.sys.repository.mapper.SysUserMenuMapper;
import org.elsfs.cloud.system.sys.service.SysUserRoleService;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/** SysUserInfoController */
@RestController
@RequestMapping("/user")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
@RequiredArgsConstructor
@Tag(description = "user", name = "用户信息管理")
public class SysUserInfoController {
  private final SysMenuService sysMenuService;
  private final SysUserRoleService sysUserRoleService;
  private final SysRoleMenuMapper sysRoleMenuMapper;
  private final SysConfigService<?> sysConfigService;
  private final SysDeptMenuMapper sysDeptMenuMapper; // 部门菜单
  private final SysUserMenuMapper sysUserMenuMapper;

  @GetMapping("getUserInfo")
  public R userInfo() {
    return R.success(SecurityUtils.getUser());
  }

  /**
   * 获取菜单树
   *
   * @return r
   */
  @GetMapping("/getMenuVue3")
  public R<?> getMenuVue3() {
    SecurityUserEntity user = SecurityUtils.getUser();
    String userId = user.getUserId();
    Set<String> menuIds = new HashSet<>();
    // 角色-菜单
    roleMenu(userId, menuIds);
    // 部门-菜单
    deptMenu(user, menuIds);
    // 用户-菜单
    userMenu(userId, menuIds);
    if (menuIds.isEmpty()) {
      return R.success();
    }

    List<SysMenu> sysMenus = sysMenuService.listByIds(menuIds);
    if (CollectionUtils.isEmpty(sysMenus)) {
      return R.success();
    }
    List<SysMenu> list =
        sysMenus.stream()
            .filter(
                sysMenu -> !Objects.equals(sysMenu.getType(), "2") // 过滤掉按钮
                )
            .sorted()
            .toList();
    return R.success(sysMenuService.getTreeVue3(list));
  }

  private void deptMenu(SecurityUserEntity user, Set<String> menuIds) {
    ConfigEntity config = sysConfigService.getConfig(SystemConfigConstantKey.ENABLE_DEPT_MENU);
    Set<String> deptIds = user.getDeptIds();
    if (config.isEnable() && CollectionUtils.isNotEmpty(deptIds)) {
      List<String> deptMenuIds = sysDeptMenuMapper.selectMenuIdsByDeptIds(deptIds);
      if (CollectionUtils.isEmpty(deptMenuIds)) {
        return;
      }
      menuIds.addAll(deptMenuIds);
    }
  }

  private void roleMenu(String userId, Set<String> menuIds) {
    // 获取用户角色 -- 获取用户角色菜单id
    ConfigEntity config = sysConfigService.getConfig(SystemConfigConstantKey.ENABLE_ROLE_MENU);
    if (config.isEnable()) {
      List<String> roleIds = sysUserRoleService.getRoleIdsByUserId(userId);
      Optional.ofNullable(roleIds)
          .filter(CollectionUtils::isNotEmpty)
          .map(sysRoleMenuMapper::selectByMenuIdByRoleIds) // 修正方法名
          .filter(CollectionUtils::isNotEmpty)
          .ifPresent(menuIds::addAll);
    }
  }

  private void userMenu(String userId, Set<String> menuIds) {
    // 获取用户角色 -- 获取用户角色菜单id
    ConfigEntity config = sysConfigService.getConfig(SystemConfigConstantKey.ENABLE_USER_MENU);
    if (config.isEnable()) {
      List<String> menuIdsByUserId = sysUserMenuMapper.selectMenuIdsByUserId(userId);
      Optional.ofNullable(menuIdsByUserId)
          .filter(CollectionUtils::isNotEmpty)
          .ifPresent(menuIds::addAll);
    }
  }
}
